
  class TreeNode {
   int val;
   TreeNode left;
    TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
public class Solution {
    StringBuilder stringBuilder = new StringBuilder();
    public String tree2str(TreeNode root) {
        if(root == null) {
            return null;
        }
        stringBuilder.append(root.val);
        if (root.left != null) {
            stringBuilder.append("(");
            tree2str(root.left);
            stringBuilder.append(")");
        } else if (root.left == null && root.right != null) {
            stringBuilder.append("(");
            stringBuilder.append(")");
        }else {
            return stringBuilder.toString();
        }
        if (root.right != null) {
            stringBuilder.append("(");
            tree2str(root.right);
            stringBuilder.append(")");
        }
        return stringBuilder.toString();
    }
}